package org.example.myframework.frame.demo.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * SSEController SSE消息推送实现
 * ＠Author: MRN
 */
@RestController
@CrossOrigin
public class SSEController {

    /**
     * 通过sse实现每三秒推送一次数据
     * @return
     */
    @GetMapping("/sse")
    public SseEmitter sse() {
        SseEmitter emitter = new SseEmitter();
        ExecutorService executor = Executors.newSingleThreadExecutor();

        emitter.onCompletion(() -> {
            System.out.println("SseEmitter completed");
            executor.shutdown();
        });

        emitter.onTimeout(() -> {
            System.out.println("SseEmitter timed out");
            emitter.complete();
            executor.shutdown();
        });

        emitter.onError((ex) -> {
            System.out.println("SseEmitter error: " + ex.getMessage());
            emitter.completeWithError(ex);
            executor.shutdown();
        });

        executor.execute(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    try {
                        emitter.send(SseEmitter.event().data("Message " + i));
                        TimeUnit.SECONDS.sleep(3);
                        System.out.println("推送第" + i + "条消息");
                    } catch (IOException e) {
                        System.out.println("Connection closed by client.");
                        emitter.completeWithError(e);
                        break;
                    }
                }
                emitter.complete();
            } catch (InterruptedException e) {
                System.out.println("SseEmitter interrupted: " + e.getMessage());
                emitter.completeWithError(e);
            } finally {
                executor.shutdown();
            }
        });

        return emitter;
    }

}
